package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.domain.OrderForm;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.SkuLockVo;
import com.spzx.product.domain.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {


    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private RabbitService rabbitService;

    //跳转结算页面接口
    @Override
    public TradeVo orderTradeData() {
        //1 创建TradeVo对象
        TradeVo tradeVo = new TradeVo();
        //2 封装需要数据
        //2.1  List<OrderItem>显示商品列表
        // 远程调用获取购物车选中商品
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> listR = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        List<CartInfo> cartInfoList = listR.getData();

        // List<CartInfo> --> List<OrderItem>
        List<OrderItem> orderItemList = null;
        if (!CollectionUtils.isEmpty(cartInfoList)) {
            orderItemList = cartInfoList.stream().map(cartInfo -> {
                OrderItem orderItem = new OrderItem();
                // cartInfo --  orderItem
                BeanUtils.copyProperties(cartInfo, orderItem);
                return orderItem;
            }).collect(Collectors.toList());
        }
        tradeVo.setOrderItemList(orderItemList);


        //2.2 计算totalAmount总金额
        BigDecimal totalAmount = new BigDecimal(0);
        //orderItemList
        for (OrderItem orderItem : orderItemList) {
            //totalAmount = totalAmount.add(单价*数量)
            //Integer skuNum = orderItem.getSkuNum();
            ///orderItem.getSkuPrice().multiply(new BigDecimal(skuNum));
            totalAmount = totalAmount.add(
                    orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        tradeVo.setTotalAmount(totalAmount);

        //订单流水号
        String tradeNo = this.generateTradeNo(userId);
        tradeVo.setTradeNo(tradeNo);

        return tradeVo;
    }

    //下单接口
    @Override
    public Long submitOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        //1 判断是否重复提交-- redis
        // 从OrderForm获取结算页面传递过来tradeNo
//        String tradeNo = orderForm.getTradeNo();
//
//        // 根据userid查询redis，redis存储tradeNo值
//        String userTradeKey = "user:tradeNo:" + userId;
//        String tradeNo_redis = (String) redisTemplate.opsForValue().get(userTradeKey);
//        //比较
//        if(!tradeNo.equals(tradeNo_redis)) { //重复提交
//            throw new ServiceException("重复提交");
//        }
//        //第一次提交，删除redis的tradeno
//        redisTemplate.delete(userTradeKey);

        //查询redis，比较，删除过程保证原子性，因为使用redis，可以直接使用redis里面lua脚本
        String userTradeKey = "user:tradeNo:" + userId;
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);

        Long flag = (Long) redisTemplate.execute(redisScript, List.of(userTradeKey), orderForm.getTradeNo());
        if (flag == 0) {
            throw new ServiceException("重复提交");
        }

        //2 检查当前购物车购买的商品价格是否最新价格 -- 远程调用接口
        //2.1 如果价格变化，提示用户
        //2.2 更新购物车价格
        //获取生成订单商品列表
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        //从orderItemList获取所有skuid
        // [1,2,3]
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());

        //远程调用：根据所有skuId查询mysql，获取所有sku对应最新价格List<SkuPrice>
        R<List<SkuPrice>> listR = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        List<SkuPrice> skuPriceList = listR.getData();

        // 比较 orderItemList的sku价格  和  skuPriceList里面sku价格是否相同
        //   skuid=1  price=100              skuid=1 price=120
        //   skuid=2  price=200              skuid=2 price=200

        //一般推荐这样做：把其中一个集合转换map，map的key就是条件，value比较值
        //               另外一个集合遍历和map比较

        // 查询所有sku最新价格的集合 skuPriceList 转换map集合
        //map的集合是skuid，value对应价格
        /**
         * [1,100]
         * [2,200]
         *
         */
        Map<Long, BigDecimal> map =
                skuPriceList.stream()
                        .collect(Collectors.toMap(SkuPrice::getSkuId,
                                SkuPrice::getSalePrice));
        //遍历orderItemList
        String priceCheckResult = "";
        for (OrderItem orderItem : orderItemList) {
            // 获取OrderItem自己价格
            BigDecimal skuPrice_self = orderItem.getSkuPrice();

            // 根据skuid获取在map集合最新价格
            BigDecimal skuPrice_new = map.get(orderItem.getSkuId());

            //把两个价格比较
            if (skuPrice_self.compareTo(skuPrice_new) != 0) {
                priceCheckResult += orderItem.getSkuName() + "价格变化了; ";
            }
        }

        //如果商品价格变化了，提示用户
        if (StringUtils.isNotEmpty(priceCheckResult)) {
            //更新购物车商品价格
            //远程调用实现：更新购物车价格
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);

            throw new ServiceException(priceCheckResult);
        }

        //3 远程调用：校验库存并锁定库存
        //String orderNo,
        //List<OrderItem> orderItemList  --  List<SkuLockVo> skuLockVoList
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).collect(Collectors.toList());

        R<String> result = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, "inner");
        String checkAndLockResult = result.getData();
        //返回字符串为空，检查锁定成功，如果返回字符串不为空，表示有商品库存不足
        if (StringUtils.isNotEmpty(checkAndLockResult)) {
            throw new ServiceException(checkAndLockResult);
        }

        //4 向订单表添加订单相关数据（两张表 order_info和order_item）-- 事务
        Long orderId = this.saveOrder(orderForm);

        //5 远程调用：删除购物车选中商品 --- redis的hash
        remoteCartService.deleteCartCheckedList(userId, "inner");

        //6 超时不支付订单自动取消 30分钟
        //延迟消息实现，RabbitMQ
        rabbitService.sendDealyMessage(
                MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId),
                MqConst.CANCEL_ORDER_DELAY_TIME
        );

        //返回订单id
        return orderId;
    }

    //调用service方法取消订单
    @Override
    public void processCloseOrder(String orderId) {
        //判断取消订单状态，如果状态是0 ，取消 状态修改为-1
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            //还原锁定的库存 ，RabbitMQ实现
            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,
                    MqConst.ROUTING_UNLOCK,
                    orderInfo.getOrderNo());
        }

    }

    //根据订单编号查询订单数据
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        //订单基本信息
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);

        //订单里面所有订单项查询
        LambdaQueryWrapper<OrderItem> wrapperOrderItem = new LambdaQueryWrapper<>();
        wrapperOrderItem.eq(OrderItem::getOrderId, orderInfo.getId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(wrapperOrderItem);
        orderInfo.setOrderItemList(orderItemList);

        return orderInfo;
    }

    //调用方法更新状态
    @Override
    public void updateOrderStatus(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo =
                orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getOrderNo, orderNo)
                        .select(OrderInfo::getId, OrderInfo::getOrderStatus));
        //未支付
        if (orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }

        //发送mq消息扣库存
        rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,
                MqConst.ROUTING_MINUS,
                orderNo);
    }

    @Override
    public Page<OrderInfo> pageOrderInfoList(Page<OrderInfo> page, Integer orderStatus) {
//        Long userId = 1L;
        Long userId = SecurityContextHolder.getUserId();

        return baseMapper.selectPageInfoList(page, orderStatus, userId);

    }


    //4 向订单表添加订单相关数据（两张表 order_info和order_item）-- 事务
    @Transactional
    public Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        //1 order_info添加一条订单数据
        OrderInfo orderInfo = new OrderInfo();
        //订单编号
        orderInfo.setOrderNo(orderForm.getTradeNo());
        //用户id
        orderInfo.setUserId(userId);
        //用户名称
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());

        UserAddress userAddress = remoteUserAddressService
                .getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        //订单总金额
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice()
                    .multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //订单状态：未支付
        orderInfo.setOrderStatus(0);
        //调用方法添加
        orderInfoMapper.insert(orderInfo);

        //2 向order_item添加订单项数据（使用第一步订单id）
        for (OrderItem orderItem : orderItemList) {
            //设置订单id
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        return orderInfo.getId();
    }

    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");

        //3.TODO 防止重复提交：将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);

        return tradeNo;
    }
}
